const express = require("express");
const router = express.Router();
const md5 = require("md5-node");
const db = require("../db.js");
const multiparty = require("multiparty");

router.get("/login", function (req, res, next) {
  res.render("login.ejs");
});
router.post("/doLogin", function (req, res, next) {
  const userName = req.body.username;
  const pas = md5(req.body.password);
  var sql = "SELECT * FROM admin where user_name=? and password=?";
  let sqlParam = [userName, pas];

  db.conn.query(sql, sqlParam, function (err, result) {
    if (err) {
      console.log("[SELECT ERROR] - ", err.message);
      return;
    }
    if (result && result.length > 0) {
      req.session.userInfo = result[0];
      req.app.locals["userInfo"] = req.session.userInfo.user_name;

      res.redirect("/admin/product");
    } else {
      res.send(
        "<script>alert('登录失败');location.href='/admin/login';</script>"
      );
    }
  });
});
router.get("/logout", function (req, res, next) {
  req.session.destroy(function (err) {
    if (err) {
      console.log(err);
    } else {
      res.redirect("/admin/login");
    }
  });
});
router.get("/product",authenLogin, function (req, res, next) {
  console.log("product");
  var sumSQL = "select count(*) as recordCount from product";
  db.conn.query(sumSQL, function (err, result) {
    if (err) return console.log(err);
    console.log(result);
    var recordCount = result[0].recordCount;
    var pageSize = 3;
    var pageCount = Math.ceil(recordCount / pageSize);
    var page = req.query.page || 1;
    var start = (page - 1) * pageSize;
    var strSQL =
      "select * from product order by id desc limit " + start + "," + pageSize;
    db.conn.query(strSQL, function (err, result) {
      if (err) {
        console.log("[SELECT ERROR]-", err.message);
        return;
      }
      res.render("product/index", {
        list: result,
        yemashu: pageCount,
        page: page,
      });
    });
  });
});

router.get("/add", authenLogin,function (req, res, next) {
  res.render("product/productadd");
});

router.post("/doAdd", authenLogin,function (req, res, next) {
  const form = new multiparty.Form();
  form.uploadDir = "./public/upload";
  form.parse(req, function (err, fields, files) {
    const title = fields.title[0];
    console.log(title);
    const cat_id = fields.cat_id[0];
    const price = fields.price[0];
    const description = fields.description[0];
    const keywords = fields.keywords[0];
    const add_time = new Date();
    const pic = files.pic[0].path.substr(7);
    console.log(pic);
    var sql =
      "insert into product(name,cat_id,price,content,image,add_time,keywords) values(?,?,?,?,?,?,?)";
    var sqlParam = [title, cat_id, price, description, pic, add_time, keywords];
    db.conn.query(sql, sqlParam, function (err, result) {
      if (err) {
        console.log("[INSERT ERROR] - ", err.message);
        return;
      }
      res.redirect("/admin/product");
    });
  });
});

router.get("/search", authenLogin,function (req, res, next) {
  var key = req.query.key;
  var strSQL = "select * from product where name like ? order by id desc";
  var strParam = ["%" + key + "%"];
  db.conn.query(strSQL, strParam, function (err, result) {
    if (err) {
      console.log("[SELECT ERROR] - ", err.message);
      return;
    }
    res.render("product/index", { list: result, page: -1, yemashu: -1 });
  });
});
router.get("/edit",authenLogin, function (req, res, next) {
  var id = req.query.id;
  var sql = "select * from product where id=?";
  var sqlParam = [id];
  db.conn.query(sql, sqlParam, function (err, result) {
    if (err) {
      console.log("[SELECT ERROR] - ", err.message);
      return;
    }
    res.render("product/productedit", { item: result[0] });
  });
});

router.post("/doEdit",authenLogin, function (req, res, next) {
  const form = new multiparty.Form();
  form.uploadDir = "public/upload";
  form.parse(req, function (err, fields, files) {
    const id = fields._id[0];
    console.log(id);
    const title = fields.title[0];
    const cat_id = fields.cat_id[0];
    const price = fields.price[0];
    const description = fields.description[0];
    const keywords = fields.keywords[0];
    const originalFilename = files.pic[0].originalFilename;
    console.log(originalFilename);
    const pic = files.pic[0].path.substr(7);
    console.log(pic);
    console.log(originalFilename.length);
    if (originalFilename.length > 0) {
      var sql =
        "update product set name=?,cat_id=?, price=?,content=?,image =?, keywords =? where id =? ";

      var sqlParam = [title, cat_id, price, description, pic, keywords, id];
    } else {
      var sql =
        "update product set name=?,cat id=?,price=?,content=?,keywords =? where id =? ";
      var sqlParam = [title, cat_id, price, description, keywords, id];
    }
    console.log(sqlParam);
    db.conn.query(sql, sqlParam, function (err, result) {
      if (err) {
        console.log("[SELECT ERROR]-", err.message);
        return;
      }
      res.redirect("/admin/product");
    });
  });
});

router.get("/delete",authenLogin, function (req, res, next) { 
  const id = req.query.id;
  var sql = "delete FROM product where id = ?";
  var sqlParam = [id];
  db.conn.query(sql, sqlParam, function (err, result) { 
    if (err) { 
      console.log("[SELECT ERROR]-", err.message);
      return;
    }
    res.redirect("/admin/product");
  });
});
function authenLogin(req, res, next) { 
  if (req.session.userInfo) { 
    next();
  } else { 
    res.redirect("/admin/login");
  }
}
module.exports = router;
